//
//  CCFileTool.m
//  BuDeJie
//
//  Created by demoncraz on 2017/2/12.
//  Copyright © 2014年 demoncraz. All rights reserved.
//  用来管理文件缓存（计算缓存大小、删除缓存文件）

#import "CCFileTool.h"
#define CachesPath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]

@implementation CCFileTool


+ (void)deleteFilesAtDirectoryPath:(NSString *)directoryPath {
    
    NSFileManager *mgr = [NSFileManager defaultManager];
    //判断文件是否存在／是否为文件夹
    
    BOOL isDirectory;
    BOOL isExist = [mgr fileExistsAtPath:directoryPath isDirectory: &isDirectory];
    if (!isExist || !isDirectory) {//如果文件不存在／不为文件夹 就报错
        NSException *exception = [NSException exceptionWithName:@"File Error" reason:@"Directory does not exist or not a directory path" userInfo:nil];
        [exception raise];
    }
    
    
    
    NSArray *subPaths = [mgr contentsOfDirectoryAtPath:directoryPath error:nil];
    for (NSString *subPath in subPaths) {
        NSString *filePath = [directoryPath stringByAppendingPathComponent:subPath];
        [mgr removeItemAtPath:filePath error:nil];
    }
}


+ (void)getFileSize:(NSString *)directoryPath completion:(void(^)(NSInteger))completion{//获取caches缓存文件总大小
    
    NSFileManager *mgr = [NSFileManager defaultManager];
    
    //判断文件是否存在／是否为文件夹
    
    
    
    //开启子线程处理获取文件大小的操作
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        BOOL isDirectory;
        BOOL isExist = [mgr fileExistsAtPath:directoryPath isDirectory: &isDirectory];
        if (!isExist || !isDirectory) {//如果文件不存在／不为文件夹 就报错
            NSException *exception = [NSException exceptionWithName:@"File Error" reason:@"Directory does not exist or not a directory path" userInfo:nil];
            [exception raise];
        }
        
        NSInteger totalSize = 0;
        NSDirectoryEnumerator *fileEnumerator = [mgr enumeratorAtPath:directoryPath];
        for (NSString *fileName in fileEnumerator) {
            
            NSString *filePath = [directoryPath stringByAppendingPathComponent:fileName];
            if ([fileName containsString:@".DS"]) continue;
            BOOL isDirectory = NO;
            BOOL isExist = [mgr fileExistsAtPath:filePath isDirectory: &isDirectory];
            
            if (!isExist || isDirectory) continue;
            
            NSDictionary *attrs = [mgr attributesOfItemAtPath:filePath error:nil];
            totalSize += [attrs fileSize];
        }
        
        if (completion) {
            dispatch_sync(dispatch_get_main_queue(), ^{
                completion(totalSize);
            });
            
        }
        
    });
    
}




@end
